import React, { useState } from 'react';
import { Upload, Modal, App } from 'antd';
import { SvgIcon } from '@/components/icon';
import { CloseOutlined } from '@ant-design/icons';
import styled from 'styled-components';

const { Dragger } = Upload;

interface ImportGuideModalProps {
  visible: boolean;
  onClose: () => void;
  onImport: (content: string) => void;
}

const StyledUploadBox = styled.div`
  .ant-upload-drag {
    border: 1px dashed #d9d9d9;
    background: #f5f5f5;
    border-radius: 16px;
    &:hover {
      border-color: #6640FF;
    }
  }
`;

const isGarbled = (str: string): boolean => {
  // 检查是否包含常见的乱码字符
  const garbledPattern = /[\uFFFD\u0000-\u0008\u000B-\u000C\u000E-\u001F]/;
  return garbledPattern.test(str);
};

const tryReadFileWithEncoding = (file: File, encodings: string[]): Promise<string> => {
  return new Promise((resolve, reject) => {
    const tryNextEncoding = (index: number) => {
      if (index >= encodings.length) {
        reject(new Error('无法正确读取文件内容'));
        return;
      }

      const reader = new FileReader();
      reader.onload = (e) => {
        const content = e.target?.result as string;
        if (!content) {
          reject(new Error('文件内容为空'));
          return;
        }

        if (!isGarbled(content)) {
          resolve(content);
        } else if (index < encodings.length - 1) {
          tryNextEncoding(index + 1);
        } else {
          reject(new Error('无法正确读取文件内容'));
        }
      };

      reader.onerror = () => {
        if (index < encodings.length - 1) {
          tryNextEncoding(index + 1);
        } else {
          reject(new Error('读取文件时发生错误'));
        }
      };

      // 尝试不同的编码
      const blob = new Blob([file], { type: 'text/plain' });
      reader.readAsText(blob, encodings[index]);
    };

    tryNextEncoding(0);
  });
};

const ImportGuideModal: React.FC<ImportGuideModalProps> = ({
  visible,
  onClose,
  onImport,
}) => {
  const [file, setFile] = useState<File>();
  const { message } = App.useApp();
  const handleUpload = (file: File) => {
    // 验证文件类型
    const fileType = file.name.split('.').pop()?.toLowerCase();
    if (fileType !== 'csv' && fileType !== 'txt') {
      message.error('文件格式不正确，只支持txt或csv文件');
    } else if (file.size > 1 * 1024 * 1024) {
      message.error('文件大小不能超过1MB');
    } else {
      setFile(file);
    }
    return false; // 阻止自动上传
  };

  const handleRemove = () => {
    setFile(undefined);
  };

  const handleOk = () => {
    if (!file) {
      message.warning('请先上传文件');
      return;
    }

    // 尝试使用不同的编码读取文件
    tryReadFileWithEncoding(file, ['UTF-8', 'GBK', 'GB18030', 'Big5'])
      .then((content) => {
        onImport(content);
        onClose();
        setFile(undefined);
      })
      .catch((error) => {
        message.error(error.message);
      });
  };

  return (
    <Modal
      title="导入引导问题"
      open={visible}
      onCancel={onClose}
      onOk={handleOk}
      width={500}
      centered
      closeIcon={<CloseOutlined className="text-[#86909C]" />}
    >
      <ul className="mb-6 list-disc pl-5 text-sm text-[#474C5F]">
        <li>只支持txt或csv文件。</li>
        <li>只支持上传一个文件，单个文件不超过1MB。</li>
        <li>问题限制最大长度为50个字符。</li>
        <li>格式说明（问题间换行处理）:</li>
        问题1<br />
        问题2<br />
        ...
      </ul>
      {file ? (
        <div className="flex h-[110px] items-center justify-between rounded-[16px] bg-[#ECEFF8] py-[16px] pl-[20px] pr-[20px]">
          <div className="truncate max-w-[80%]">{file.name}</div>
          <a className="!text-[#FF4C40] flex-shrink-0" onClick={handleRemove}>
            删除
          </a>
        </div>
      ) : (
        <StyledUploadBox>
          <Dragger maxCount={1} beforeUpload={handleUpload} accept=".txt,.csv">
            <div className="flex h-[78px] flex-col items-center justify-center">
              <SvgIcon icon="icon-upload" size={32} />
              <div className="mt-1 text-center text-[#474C5F]">上传 txt/csv 文件</div>
            </div>
          </Dragger>
        </StyledUploadBox>
      )}
    </Modal>
  );
};

export default ImportGuideModal; 